package com.pj.common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.KeyboardUtils
import com.pj.common.R
import com.pj.common.extension.MsgEvent
import com.qmuiteam.qmui.widget.QMUIEmptyView
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import java.lang.reflect.ParameterizedType

/**
 * Create by wuyt on 2020/1/6 12:08
 * {@link }
 */
abstract class BaseFragment<VM : BaseViewModel, VDB : ViewDataBinding> : Fragment(), IFragment {

    lateinit var mViewModel: VM
    lateinit var mBinding: VDB
    var tipDialog: QMUITipDialog? = null
    var emptyView: QMUIEmptyView? = null

    //是否第一次加载
    private var isFirst: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
        setHasOptionsMenu(true)
        requireActivity().apply {
            //键盘事件注册
            KeyboardUtils.registerSoftInputChangedListener(this) {
                onSoftInputChanged(it)
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
        mBinding.lifecycleOwner = viewLifecycleOwner
        tipDialog = QMUITipDialog.Builder(requireActivity())
            .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
            .setTipWord("正在加载")
            .create()
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onVisible()
        createViewModel()
        registerUIChange()
        initData(view, savedInstanceState)
        subscribeUi()
    }

    override fun onResume() {
        super.onResume()
        onVisible()
    }

    override fun onDestroy() {
        super.onDestroy()
        //activity?.run { KeyboardUtils.unregisterSoftInputChangedListener(window) }
    }

    /**
     * 是否需要懒加载
     */
    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            lazyLoadData()
            isFirst = false
        }
    }

    /**
     * 注册UI事件
     */
    private fun registerUIChange() {

        emptyView = mBinding.root.findViewById(R.id.empty_view)
        mViewModel.uiEmpty.observe(viewLifecycleOwner) {

        }
        mViewModel.uiLoading.observe(viewLifecycleOwner) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
        mViewModel.msgEvent.observe(viewLifecycleOwner) {
            messageEvent(it)
        }
    }

    protected open fun messageEvent(msg: MsgEvent) {

    }

    fun showLoading() {
        tipDialog?.show()
    }

    fun hideLoading() {
        tipDialog?.hide()
    }


    /**
     * 创建 ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val tp = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
        mViewModel = if (activityViewModel()) {
            ViewModelProvider(requireActivity(), ViewModelFactory()).get(tClass) as VM
        } else {
            ViewModelProvider(this, ViewModelFactory()).get(tClass) as VM
        }
        lifecycle.addObserver(mViewModel)
    }
}